import uiautomator2 as u2
import time
import random
import signal
import sys
import datetime


class AutoSwipeVideos:
    def __init__(self, device_name=None):
        # 连接设备，device_name为空则自动连接
        if device_name:
            self.d = u2.connect(device_name)
        else:
            self.d = u2.connect()

        # 确保屏幕是亮着的
        self.d.screen_on()

        # 初始化变量
        self.running = True
        # 滑动次数
        self.swipe_count = 0
        # 总观看时间
        self.total_watch_time = 0

        # 注册信号处理，用于优雅退出
        signal.signal(signal.SIGINT, self.stop)
        signal.signal(signal.SIGTERM, self.stop)

        print("设备已连接，准备开始自动刷视频...")
        print("按Ctrl+C停止程序")

    def stop(self, signum, frame):
        """停止程序"""
        print(f"\n程序已停止，共滑动了{self.swipe_count}次视频")
        self.running = False
        sys.exit(0)

    def random_sleep(self, min_sec=3, max_sec=6):
        """随机休眠一段时间，模拟观看视频"""
        sleep_time = random.uniform(min_sec, max_sec)
        time.sleep(sleep_time)
        return sleep_time

    def swipe_up(self):
        """向上滑动屏幕，切换到下一个视频"""
        # 获取屏幕尺寸
        width, height = self.d.window_size()

        # 随机生成滑动起点和终点，增加随机性
        start_x = random.uniform(width * 0.4, width * 0.6)
        start_y = random.uniform(height * 0.7, height * 0.8)
        end_x = random.uniform(width * 0.4, width * 0.6)
        end_y = random.uniform(height * 0.2, height * 0.3)

        # 随机滑动 duration
        duration = random.uniform(0.2, 0.4)

        # 执行滑动操作
        self.d.swipe(start_x, start_y, end_x, end_y, duration=duration)
        self.swipe_count += 1

        print(f"{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} 已滑动 {self.swipe_count} 次，下一个视频...")

    def start_watching(self, app_package=None):
        """开始自动观看视频"""
        # 如果指定了应用包名，则打开该应用
        if app_package:
            try:
                print(f"打开应用: {app_package}")
                self.d.app_start(app_package)
                # 等待应用启动
                time.sleep(5)
            except Exception as e:
                print(f"打开应用失败: {e}")
                return

        # 开始循环滑动
        while self.running:
            try:
                # 随机时间观看当前视频
                watch_time = self.random_sleep()
                self.total_watch_time+=watch_time
                print(f"观看了 {watch_time:.2f} 秒 总观看时长：{self.total_watch_time/60:.2f} 分")

                # 滑动到下一个视频
                self.swipe_up()

                # 随机小停顿，模拟人工操作间隔
                time.sleep(random.uniform(0.2, 0.5))

            except Exception as e:
                print(f"发生错误: {e}")
                # 出错时停顿一下再继续
                time.sleep(3)


if __name__ == "__main__":
    # 可以指定设备名称，如通过adb devices查看的设备ID
    # device_id = "your_device_id_here"

    # 可以指定应用包名，如抖音是"com.ss.android.ugc.aweme"
    # app_package = "com.ss.android.ugc.aweme"  # 抖音
    # app_package = "com.kuaishou.nebula"     # 快手

    # 创建实例并开始
    auto_swipter = AutoSwipeVideos()
    # 如果要指定应用，可以传入app_package参数
    auto_swipter.start_watching()
